package com.howie.hmvc.request;

import java.text.DecimalFormat;

import javax.servlet.http.HttpSession;

import lombok.Getter;

import org.apache.commons.fileupload.ProgressListener;

public class FileProgressListener implements ProgressListener{

	public static final String FILE_INFO_KEY = "fileInfo";
	
	private HttpSession session;
	
	public FileProgressListener(HttpSession session){
		this.session = session;
		session.setAttribute(FILE_INFO_KEY,new FileInfo());
	}
	
	@Override
	public void update(long bytesRead,long contentLength,int fileIndex){
		FileInfo fileInfo = (FileInfo)session.getAttribute(FILE_INFO_KEY);
		fileInfo.update(bytesRead, contentLength);
	}

	public static class FileInfo{
		/* 已读取大小 */
		private long readSize;
		/* 完成百分比 */
		@Getter
		private long rate;
		/* 上传速度 */
		private double speed;
		//开始时间
		private long startTime = System.currentTimeMillis();
		private static DecimalFormat df = new DecimalFormat("#.##");
		
		public void update(long bytesRead,long contentLength){
			readSize = bytesRead;
			rate = (long)(((double)readSize)/((double)contentLength)*100);
			//计算上传速度 B/秒
			Long currTIme = System.currentTimeMillis();
			speed = ((double)bytesRead)/(((double)currTIme-(double)startTime)/1000);
		}
		
		public String getReadSize(){
			return sizeToStr(readSize);
		}
		
		public String getSpeed(){
			return sizeToStr(speed)+"/秒";
		}
		
		private String sizeToStr(double size){
			double gb = 1024D * 1024D * 1024D;
			double mb = 1024D * 1024D;
			double kb = 1024D;
			if(size >= gb){
				return df.format(size/gb) + " GB";
			}
			if(size >= mb){
				return df.format(size/mb) + " MB";
			}
			if(size >= kb){
				return df.format(size/kb) + " KB";
			}
			return size + " B";
		}
	}
}
